package smodul

import (
	"WeChatMGRA/requests"
	"gitee.com/yutiandou/wdtools/wdevent"
	"gitee.com/yutiandou/wdtools/wdlog"
	"sync"
	"time"
)


var automaticEnd = wdevent.NewTimeEvent(time.Second * 5 * 60)

//robotlist 当前正在工作的机器人集合
type robotlist struct {
	robors map[string]*Robots
	mutex sync.RWMutex
}

func NewRobotManage()*robotlist{
	rs := &robotlist{
		robors:make(map[string]*Robots),
		mutex:sync.RWMutex{},
	}
	automaticEnd.AddEvent("robotlist_AutomaticRemove",60*10,true,func(nowtime int64){
		rs.RemoveTimeoutMachine(nowtime)
	})
	wdevent.AddEvent("MysqlConnectSuccess",rs.DataInit)
	wdevent.AddEvent("gameover", func(data interface{}){
		rs.GameOver()
	})
	return  rs
}
func (r * robotlist) AddRobot(robot * Robots){
	r.mutex.Lock()
	go robot.TransmitMsg()
	r.robors[robot.Wcid] = robot
	r.mutex.Unlock()
}
func (r * robotlist)RemoveRobot(robot * Robots){
	r.mutex.Lock()
	r.robors[robot.Wcid] = robot
	r.mutex.Unlock()
}
func (r * robotlist) DataInit(date interface{}){
	rs,err := Get_All_Working_Robots()
	if wdlog.PanicErr(err){
	}
	for k,_:=range rs {
		rs[k].StrGroupsToSliGroups()
		r.AddRobot(rs[k])
	}
	wdlog.Warning("机器人从数据库加载完毕")
}

//RobotForcedOffline 强制下线  0：成功   1：机器人未上线
func (r * robotlist)RobotForcedOffline(id uint)int{
	wcid := "null"
	r.mutex.RLock()
	for k,v:= range r.robors{
		if v.ID == id{
			wcid = k
			break
		}
	}
	r.mutex.RUnlock()
	r.mutex.Lock()
	if wcid != "null"{
		if rob,ok:=r.robors[wcid];ok{
			//rob.WorkStat = 1
			rob.Online = 1
			rob.ForcedUpdate()
			NewRecordAndInsert(rob.ID,rob.NickName,rob.Creator,"机器人被强制下线")
			requests.QuitWx(rob.Wid)
			delete(r.robors,wcid)
			r.mutex.Unlock()
			return 0
		}else {
			robot := new(Robots)
			robot.ID = id
			robot.Online = 1
			if robot.Updata(2)==1{
				return 0
			}
		}
	}
	r.mutex.Unlock()
	return 1
}


func (r * robotlist) GameOver(){
	r.mutex.Lock()
	for _,v:=range r.robors{
		v.ForcedUpdate()
	}
	r.mutex.Unlock()
	wdlog.Warning("当前工作机器人数据已导入数据库...")
	wdevent.ExecEvent("DataStoreToMysql",nil)
}
func (r * robotlist)First(wcid string)(robot * Robots){
	r.mutex.RLock()
	if rob,ok := r.robors[wcid];ok{
		robot = rob
	}else{
		robot = nil
	}
	r.mutex.RUnlock()
	return
}

//RemoveTimeoutMachine 机器人超时后移除
func (r*robotlist)RemoveTimeoutMachine(nowtime int64){
	keys := make([]string,0)
	r.mutex.RLock()
	for k,v:= range r.robors{
		if nowtime>=v.StartTime+v.WorkTime{
			keys = append(keys,k)
		}
	}
	r.mutex.RUnlock()
	r.mutex.Lock()
	for _,k:=range keys{
		robot:=r.robors[k]
		robot.DataInit()
		NewRecordAndInsert(robot.ID,robot.NickName,robot.Creator,"机器人工作结束")
		delete(r.robors,k)
		//wdevent.ExecEvent("RobotRemoveSuccess",robot)
	}
	r.mutex.Unlock()
}